package org.action;

import com.opensymphony.xwork2.ActionSupport;
import org.json.simple.JSONValue;
import org.model.Floor;
import org.model.User;
import org.service.ForumService;
import org.service.UserService;
import org.util.Base64;
import org.util.Sha1;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by tedzy on 2015/5/17.
 * 默认动作库。
 */
public class DefaultAction extends ActionSupport {
    private int uid;
    private String jsonResult;
    private UserService userService;
    private ForumService forumService;
    private String input;
    private String key;
    private int x;
    private int y;
    private int w;
    //==========CONFIG START=============
    private String $bucket = "honoka";
    private String $sk = "CRKIRJJnpNWl4uIThf9FBZXgx_UKq5dGYA9d3Ajx";
    private String $ak = "Blqo2rQ4sYCwJqSE5cGRRaBcjjOUHSD-rTLUMIWs";
    private String $upapi = "http://upload.qiniu.com";
    private String $domain = "http://honoka.qiniudn.com/";
    //==========CONFIG END===============

    public String getUsername(){
        User user = userService.getUser(uid);
        jsonResult = user.getUsername();
        return SUCCESS;
    }

    public String getAvatar(){
        User user = userService.getUser(uid);
        jsonResult =  user.getAvatar();
        return SUCCESS;
    }

    public String getThreadLastNameAndReply(){
        if(input==null||input.equals("")){
            jsonResult = "";
            return SUCCESS;
        }
        String[] s = input.split(",");
        Floor floor = forumService.readFloors(s[s.length - 1]).get(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String time = sdf.format(floor.getPostTime());
        User user = userService.getUser(floor.getAuthor());

        jsonResult = "<div class=\"po-reply-name\" id=\"po-name\">\n" +
                "         <a href=\"wiki/User:"+ user.getUsername() +"\">" + user.getUsername() + "</a>\n" +
                "     </div>\n" +
                "     <div class=\"clear\"></div>\n" +
                "     <div class=\"last-reply-time\" id=\"last-reply-time\">\n" +
                "         " + time +"\n" +
                "     </div>";
        return SUCCESS;
    }

    /**
     * 获得一个上传凭证
     * URL: /getuploadtoken.json
     * 输入: input 文件名
     * @return token 上传凭证
     *          key 文件保存的key
     *          upapi 上传地址
     *          domain 取回地址
     */
    public String getUploadToken(){
        Calendar ca = Calendar.getInstance();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddhhmmssS");
        String res = sf.format(ca.getTime());
        input = input==null?"img":input.equals("")?"img":input;
        String key = res + "/" + input + ".jpg";

        //构造上传凭证
        Map<String, Object> policy = new LinkedHashMap<>();
        policy.put("scope", $bucket + ":" + key);
        policy.put("deadline", System.currentTimeMillis()/1000+1000);
        policy.put("returnBody", "{\"key\":$(key),\"name\":$(fname),\"size\":$(fsize),\"hash\":$(etag)}");
        policy.put("fsizeLimit", 10*1024*1024);
        policy.put("mimeLimit", "image/*");

        String encodePolicy = Base64.urlSafeBase64Encode(JSONValue.toJSONString(policy));
        String encodeSign = Base64.encode(Sha1.hmacSha1(encodePolicy, $sk));
        String token = $ak + ":" + encodeSign + ":" + encodePolicy;

        Map<String, Object> json = new LinkedHashMap<>();
        json.put("token", token);
        json.put("key", key);
        json.put("upapi", $upapi);
        json.put("domain", $domain);

        jsonResult = JSONValue.toJSONString(json);
        return SUCCESS;
    }

    /**
     * 获得一个头像裁剪凭证
     * @return queryurl 头像裁剪地址
     *          avatarurl 头像目标地址
     *          result success 成功，error 失败
     *          info 失败时表示失败原因。
     */
    public String cropAvatarToken(){
        Map<String, Object> json = new LinkedHashMap<>();
        boolean check = true;
        if(key==null||key.equals("")){
            json.put("result", "error");
            json.put("info", "key不能为空。");
            check = false;
        }
        if(check){
            String downloadURL = $domain + key;
            String resourceURL = downloadURL.substring(7);
            String cropURL = resourceURL + "?imageMogr2/crop/!" + w + "x" + w + "a" + x + "a" + y + "/strip/thumbnail/150x150|saveas/";
            String encodedEntryURI = Base64.urlSafeBase64Encode($bucket + ":" + key);
            String waitforsignURL = cropURL + encodedEntryURI;
            String sign = Base64.encode(Sha1.hmacSha1(waitforsignURL, $sk));
            String finalURL = waitforsignURL + "/sign/" + $ak + ":" +sign;

            json.put("result", "success");
            json.put("queryurl", "http://"+finalURL);
            json.put("avatarurl", downloadURL);
        }

        jsonResult = JSONValue.toJSONString(json);
        return SUCCESS;
    }

    public String getRandomNavImage(){
        String[] randomImages = {"http://honoka.qiniudn.com/20150523030803770/index-nav.jpg",
                "http://honoka.qiniudn.com/20150523030855444/help-nav.jpg",
                "http://honoka.qiniudn.com/20150523030934845/login-nav.jpg",
                "http://honoka.qiniudn.com/20150523031111285/bbs-nav.jpg",
                "http://honoka.qiniudn.com/20150523031159479/register-nav.jpg",
                "http://honoka.qiniudn.com/20150524054546648/6.jpg",
                "http://honoka.qiniudn.com/2015052405460479/9.jpg",
                "http://honoka.qiniudn.com/20150524054636462/10.jpg",
                "http://honoka.qiniudn.com/20150525024245221/img_2550.jpg"
        };
        int len = randomImages.length;
        Random rand = new Random();
        jsonResult = randomImages[rand.nextInt(len)];
        return SUCCESS;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getJsonResult() {
        return jsonResult;
    }

    public void setJsonResult(String jsonResult) {
        this.jsonResult = jsonResult;
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public ForumService getForumService() {
        return forumService;
    }

    public void setForumService(ForumService forumService) {
        this.forumService = forumService;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getW() {
        return w;
    }

    public void setW(int w) {
        this.w = w;
    }
}
